package com.example.zpc.file.service;

import android.content.Context;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import dev.dworks.apps.anexplorer.model.DocumentInfo;

/**
 * Created by LT on 2017/6/28.
 */

public class SocketServer {
    DocumentInfo doc;
    private ServerSocket ss;
    InputStream inputStream;
    Context context;

//    private static class SocketServerHolder {
//        static final SocketServer server=new SocketServer();
//    }
//
//    public static SocketServer getInstance() {
//        return SocketServerHolder.server;
//    }
//
//    private SocketServer() {
//
//    }
//
//    private Object readInstance() {
//        return getInstance();
//    }
//    public static SocketServer instance() {
//        if (SocketServer.skserver == null) {
//            SocketServer.skserver = new SocketServer();
//        }
//        return SocketServer.skserver;
//
//    }
    public SocketServer( Context context) {
        this.context = context;

    }

    public void setContext(Context context) {
        this.context = context;
    }

    public void setDoc(DocumentInfo doc) {
        this.doc = doc;
        try {
            inputStream = context.getContentResolver().openInputStream(doc.derivedUri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void service() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ss = new ServerSocket(8888);
                    while (true) {
                        Socket socket = null;
                        try {
                            ExecutorService executorService = Executors.newFixedThreadPool(10);
                            System.out.println("服务已启动");
                            socket = ss.accept();
                            executorService.execute(new Handler(socket));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                }
            }
        }).start();


    }
//    public  void main(String[] args) {
//        SocketServer sst = new SocketServer();
//        sst.service();
//    }

    class Handler implements Runnable {

        private Socket socket;

        public Handler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                //String path = "D://self//aria2//cc_bd.mp4";
                String requestHeader;
                long stIndex = 0;
                BufferedReader bd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while ((requestHeader = bd.readLine()) != null && !requestHeader.isEmpty()) {
                    System.out.println(requestHeader);
                    if (requestHeader.contains("Range: bytes=")) {
                        try {
                            stIndex = Long.parseLong(requestHeader.substring("Range: bytes=".length(), requestHeader.length() - 1));
                        } catch (Exception e) {
                        }
                    }
                }
                //ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                //File fi = new File(path.);
                System.out.println("文件跳过:" + stIndex);
                System.out.println("文件长度:" + doc.size);
                DataInputStream fis = new DataInputStream(new BufferedInputStream(inputStream));
                // DataInputStream fis = new DataInputStream(new ByteArrayInputStream(bytes));
                fis.skip(stIndex);
                DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
                PrintWriter pw = new PrintWriter(socket.getOutputStream());
                if (stIndex == 0) {
                    pw.println("HTTP/1.1 200 OK");
                } else {
                    pw.println("HTTP/1.1 206 Partial Content");
                }
                pw.println("Accept-Ranges:bytes");
                pw.println("Content-type:video/mp4");
                pw.println("Etag:W/\"835659632-1490067461759\"");
                pw.println("Content-Length:" + (doc.size - stIndex));
                pw.println("Content-Range:bytes " + stIndex + "-" + (doc.size - 1) + "/" + doc.size);//Content-Range:bytes 2489469-835659631/835659632
                pw.println("Content-Disposition:inline;filename=cc_bd.mp4");
                pw.println();
                pw.flush();
                int bufferSize = 1024 * 1024;
                byte[] buf = new byte[bufferSize];
                while (true) {
                    int read = 0;
                    if (fis != null) {
                        read = fis.read(buf);
                    }
                    if (read == -1) {
                        break;
                    }
                    dout.write(buf, 0, read);
                }
                dout.flush();
                fis.close();
                socket.close();
                System.out.println("文件传输完成");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
